/*********************************************************************************
 *      Copyright:  (C) 2025 iot25<lingyun@email.com>
 *                  All rights reserved.
 *
 *       Filename:  sqlite_database.c
 *    Description:  This file sqlite_database.c
 *                 
 *        Version:  1.0.0(01/05/25)
 *         Author:  iot25 <lingyun@email.com>
 *      ChangeLog:  1, Release initial version on "01/05/25 09:33:56"
 *                 
 *******************************************************************************/
#include<stdio.h>
#include <sqlite3.h>
#include<stdlib.h>
#include<string.h>

#include"logger.h"
#include"sqlite_database.h"


int create_db(char *db_name)
{
	int 				result;
	char				sql[256];
	char				*errmsg;

	//创建sqlite数据表，并打开连接
	result = sqlite3_open(db_name, &db);
	if(result != SQLITE_OK)
	{
		log_error("Failed to open sqlite database: %s\n", sqlite3_errmsg(db));
		return -1;
	}
	else
	{
		log_debug( "Open sqlite database successfully!\n");
	}

	//创建表格ds18b20_data
	snprintf(sql, sizeof(sql), "create table if not exists ds18b20_data_server (rowid INTEGER PRIMARY KEY,device_id TEXT NOT NULL,temperature TEXT NUT NULL,time_now TEXT NOT NULL);");
	result = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
	if(result != SQLITE_OK)
	{
		log_error("Creat table ds18b20_data failure: %s\n", errmsg);
		sqlite3_free(errmsg);
		return -1;
	}
		log_debug("Creat table ds18b20_data sucessfully!\n");
		return 0;
}

	//插入数据
int insert_data(sqlite3 *db, char *device_id, char *temperature, char *sample_time)
{
	char					sql[512];
	int						result=0;
	char					*errmsg = NULL;

	snprintf(sql, sizeof(sql), "INSERT INTO ds18b20_data_server (device_id, temperature, time_now) VALUES ('%s','%s','%s');", device_id, temperature, sample_time);
	
	result = sqlite3_exec(db, sql, NULL, 0, &errmsg);
	if(result != SQLITE_OK)
	{
		log_error("Insert data failure: %s\n", errmsg);
		sqlite3_free(errmsg);
		return -1;
	}
		log_debug("Insert data to table ds18b20_data sucessfully!\n");
		return 0;
}

